package br.com.cfccultura.admin.control.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.cfccultura.admin.model.dao.ICalendarioDAO;
import br.com.cfccultura.admin.model.enums.Periodo;
import br.com.cfccultura.admin.model.enums.SimNao;
import br.com.cfccultura.admin.model.vo.CalendarioDia;
import br.com.cfccultura.admin.model.vo.Turma;

@Repository
public class CalculoDataTurma {
	
	@Autowired
	private ICalendarioDAO calendarioDAO;
	
	public List<CalendarioDia> getDataTermino(Turma vo) {
		
		List<CalendarioDia> calendario = new ArrayList<CalendarioDia>();
		
		if(!vo.getPeriodo().isFinalSemana()) {
		/**
		 * Calcula data termino em dias uteis
		 */	
			int totalDias = vo.getCurso().getCargaHoraria() / 5;
			Calendar c = Calendar.getInstance();
			c.setTime(vo.getInicio());
			for(int i=1;i<totalDias; i++) {
				c.add(Calendar.DAY_OF_MONTH, 1);
				verificaFeriado(c, 1, true);
				calendario.add(new CalendarioDia(c.getTime()));
			}		
		} else {
		/**
		 * Calcula data termino em final de semana
		 */
			int totalDias = vo.getCurso().getCargaHoraria() / 10;
			if(vo.getCurso().getCargaHoraria() % 10 > 1) {
				totalDias++;
			}
			Calendar c = Calendar.getInstance();
			c.setTime(vo.getInicio());
			
			for(int i=1;i<totalDias; i++) {
				if(!vo.getPeriodo().equals(Periodo.SABeDOM)) {
					c.add(Calendar.DAY_OF_MONTH, 7);
					verificaFeriado(c, 7, false);
				} else {
					if(c.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
						throw new RuntimeException("Data Invalida! Data inicial tem q ser sabado!");
					}
					
					verificaFeriado(c, 1, false);
					i++;
					if(i < totalDias)
						verificaFeriado(c, 6, false);
				}
				calendario.add(new CalendarioDia(c.getTime()));
			}			
		}
		return calendario;
	}
	
	private void verificaFinalSemana(Calendar c) {
		if(c.get(Calendar.DAY_OF_WEEK) == 1) { //DOMINGO
			c.add(Calendar.DAY_OF_MONTH, 1);
		} else if(c.get(Calendar.DAY_OF_WEEK) == 7) { //SABADO
			c.add(Calendar.DAY_OF_MONTH, 2);
		}
	}
	
	private void verificaFeriado(Calendar c, Integer qtdeDias, Boolean verificaFinalSemana) {
		CalendarioDia dia = getCalendarioDAO().consultar(c.getTime());
		if(dia.getFeriado().equals(SimNao.SIM)) {
			c.add(Calendar.DAY_OF_MONTH, qtdeDias);
			if(verificaFinalSemana)
				verificaFinalSemana(c);
		} else {
			if(verificaFinalSemana)
				verificaFinalSemana(c);			
		}
	}
	
	public ICalendarioDAO getCalendarioDAO() {
		return calendarioDAO;
	}
	public void setCalendarioDAO(ICalendarioDAO calendarioDAO) {
		this.calendarioDAO = calendarioDAO;
	}

}
